import axios from 'axios';
import qs from 'qs';

const axiosInstance = axios.create({
    timeout: 5000,
    baseURL: 'http://localhost:9099/api/',
    headers: {
        'X-ACCESS-TOKEN': 'mock_token',
        'Content-Type': 'application/json'
    },
});

// 请求拦截器
axiosInstance.interceptors.request.use(
    config => {
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
    response => {
        // 0是data中的成功响应码
        if (200 === response.status && response.data && 0 === response.data.code) {
            return Promise.resolve(response);
        } else {
            return Promise.reject(response);
        }
    },
    error => {
        console.log('error=>' + error)
        alert(`异常请求：${qs.stringify(error.message)}`)
    }
);

export default {
    post(url, data) {
        return new Promise((resolve, reject) => {
            axiosInstance({
                method: 'POST',
                url,
                data: qs.stringify(data),
            }).then(res => {
                resolve(res.data)
            }).catch(err => {
                reject(err)
            });
        })
    },

    get(url, data) {
        return new Promise((resolve, reject) => {
            axiosInstance({
                method: 'GET',
                url,
                params: data,
            }).then(res => {
                resolve(res.data)
            }).catch(err => {
                reject(err)
            })
        })
    }
};